<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Db;
use app\model\Order;

class Course extends controller
{
    protected $middleware = [
        'check' => [
            'only' => ['buy']
        ]
    ];

    public function getCourseList(Request $request)
    {
        $category_id = $request->get('category_id', 0, 'intval');
        $page = $request->get('page', 1, 'intval');
        $page = $page > 0 ? $page : 1;
        $course = Db('course')->alias('c')->join('category ct','c.category_id = ct.category_id','LEFT');
        if ($category_id) {
            $course->where('c.category_id', $category_id);
        }
        $list = $course
            ->where('c.status', 1)
            ->where('c.start_time', 'gt', date('Y-m-d'))
            ->field('c.course_id,c.name,c.image,c.price,c.start_time,c.end_time,c.address,c.description,ct.name as category_name')
            ->order('c.course_id desc')
            ->page($page, 10)
            ->select();
        $token = $request->param('token');
        if ($token && $user = Db('user')->where('token', $token)->field('token', true)->find()) {
            $course_ids = Db('order')->where('user_id', $user['user_id'])->where('status', 1)->column('course_id');
            foreach ($list as $key => $val) {
                if (in_array($val['course_id'], $course_ids)) {
                    $list[$key]['is_buy'] = 1;
                } else {
                    $course[$key]['is_buy'] = 0;
                }
            }
        }
        return ['code' => 0, 'data' => $list];
    }

    public function getCourseInfo(Request $request)
    {
        $course_id = $request->get('course_id', 0, 'intval');
        $info = Db('course')
            ->alias('c')
            ->join('teacher t', 'c.teacher_id = t.teacher_id', 'LEFT')
            ->join('category ca', 'c.category_id = ca.category_id', 'LEFT')
            ->field('c.*,t.name as teacher_name,t.avatar as teacher_avatar,t.age as teacher_age,ca.name as category_name')
            ->where('c.course_id', $course_id)
            ->find();
        if (!$info) {
            return ['code' => 2, 'msg' => '课程已下架'];
        }
        $info['num'] = Db('order')->where('status', 1)->where('course_id', $course_id)->count();
        $token = $request->param('token');
        if ($token && $user = Db('user')->where('token', $token)->field('token', true)->find()) {
            $course_ids = Db('order')->where('user_id', $user['user_id'])->where('status', 1)->column('course_id');
            if (in_array($course_id, $course_ids)) {
                $info['is_buy'] = 1;
            } else {
                $info['is_buy'] = 0;
            }
        }
        return ['code' => 0, 'data' => $info];
    }

    public function buy(Request $request)
    {
        $course_id = $request->post('course_id', 0, 'intval');
        $num = $request->post('num', 1, 'intval');
        $company = $request->post('company', '', 'trim');
        $contact = $request->post('contact', '', 'trim');
        $phone = $request->post('phone', '', 'trim');
        $sex = $request->post('sex', 1, 'intval');
        $position = $request->post('position', '', 'trim');
        $address = $request->post('address', '', 'trim');
        $admin_name = $request->post('admin_name', '', 'trim');
        Db::startTrans();
        $course = Db('course')->where('course_id', $course_id)->where('status', 1)->find();
        if (!$course) {
            Db::rollback();
            return ['code' => 3, 'msg' => '课程已下架'];
        }
        $order = Db('order')->where('course_id', $course_id)->where('user_id', $request->user['user_id'])->where('status', 1)->find();
        if ($order) {
            Db::rollback();
            return ['code' => 3, 'msg' => '请勿重复购买'];
        }
        if ($num <= 0) {
            Db::rollback();
            return ['code' => 4, 'msg' => '请选择上课人数'];
        }
        if ($company == '') {
            Db::rollback();
            return ['code' => 4, 'msg' => '请填写公司名称'];
        }
        if ($contact == '') {
            Db::rollback();
            return ['code' => 4, 'msg' => '请填写联系人姓名'];
        }
        if (!in_array($sex, [1, 2])) {
            Db::rollback();
            return ['code' => 4, 'msg' => '请选择联系人性别'];
        }
        if ($phone == '' || !preg_match('/^1\d{10}$/', $phone)) {
            Db::rollback();
            return ['code' => 4, 'msg' => '请填写正确的联系电话'];
        }
        if ($position == '') {
            Db::rollback();
            return ['code' => 4, 'msg' => '请填写公司职务'];
        }
        if ($address == '') {
            Db::rollback();
            return ['code' => 4, 'msg' => '请填写公司地址'];
        }
        if ($admin_name == '') {
            Db::rollback();
            return ['code' => 4, 'msg' => '请填写推荐人姓名'];
        }
        $transaction = Order::getTransaction();
        $order_data = [
            'user_id' => $request->user['user_id'],
            'transaction' => $transaction,
            'course_id' => $course_id,
            'price' => $course['price'] * $num,
            'num' => $num,
            'course_price' => $course['price'],
            'course_name' => $course['name'],
            'course_image' => $course['image'],
            'company' => $company,
            'contact' => $contact,
            'phone' => $phone,
            'sex' => $sex,
            'position' => $position,
            'address' => $address,
            'create_time' => date('Y-m-d H:i:s'),
            'status' => 0
        ];
        $order_id = Db('order')->insert($order_data, false, true);
        if ($order_id) {
            $order_member = [
                'order_id' => $order_id,
                'course_id' => $course_id,
                'company' => $company,
                'contact' => $contact,
                'phone' => $phone,
                'sex' => $sex,
                'position' => $position,
                'address' => $address,
            ];
            if (!Db('orderMember')->insert($order_member)) {
                Db::rollback();
                return ['code' => 3, 'msg' => '下单失败'];
            }
            $user = [];
            if ($request->user['name'] == '') {
                $user = [
                    'company' => $company,
                    'name' => $contact,
                    'phone' => $phone,
                    'sex' => $sex,
                    'position' => $position,
                    'address' => $address,
                ];
            }
            if (!$request->user['admin_id']) {
                $admin_id = Db('admin')->where('nickname', $admin_name)->value('admin_id');
                $user['admin_id'] = $admin_id;
            }
            if (!empty($user)) {
                Db('user')->where('user_id', $request->user['user_id'])->update($user);
            }
            Db::commit();
            return ['code' => 0, 'data' => ['order_id' => $order_id]];
        } else {
            Db::rollback();
            return ['code' => 2, 'msg' => '下单失败'];
        }
    }

}